'use strict';

module.exports = (app) => {
  class RecruitService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { Recruit } = app.model.Tables.Web;
      const data = ctx.request.body;
      const res = await Recruit.create({
        name: data.name,
        requirement: data.requirement,
        desc: data.desc,
        salary: data.salary,
        phone: data.phone,
        address: data.address,
        projectId: ctx.adminInfo.project_id,
      });

      return res;
    }

    async delete() {
      const { app, ctx } = this;
      const { Recruit } = app.model.Tables.Web;
      const { id } = ctx.params;
      const res = await Recruit.destroy({
        where: {
          id,
          projectId: ctx.adminInfo.project_id,
        },
      });
      if (res) {
        return '删除成功';
      }
      return 'id不存在,删除失败';
    }

    async update() {
      const { app, ctx } = this;
      const { ProjectAdmin, Recruit, Admin } = app.model.Tables.Web;
      const data = ctx.request.body;
      // 获取token
      const token = ctx.get('authorization');
      // const adminRes = await Admin.findOne({
      //   where: {
      //     access_token: token,
      //   },
      // });
      // 根据token查找项目id
      // const projectRes = await ProjectAdmin.findOne({
      //   where: {
      //     adminId: adminRes.dataValues.id,
      //   },
      // });
      const res = await Recruit.update(
        {
          name: data.name,
          requirement: data.requirement,
          desc: data.desc,
          salary: data.salary,
          phone: data.phone,
          address: data.address,
          projectId: ctx.adminInfo.project_id,
        },
        {
          where: {
            id: data.id,
            projectId: ctx.adminInfo.project_id,
          },
        }
      );
      if (res[0]) {
        return '修改成功';
      }
      return 'id不存在,修改失败';
    }

    async getAll() {
      const { app, ctx } = this;
      const { Recruit } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await Recruit.findAndCountAll({
        where: {
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
        limit: Number(data.limit) || 10,
        offset: Number(data.offset) || 0,
      });

      return res;
    }

    async getById() {
      const { app, ctx } = this;
      const { Recruit } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await Recruit.findOne({
        where: {
          id: data.id,
        },
      });

      return res;
    }
  }

  return RecruitService;
};
